package me.zhulu.executor;

import me.zhulu.quartz.dynamicjob.MyTask;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdScheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.CronTriggerBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: herosea
 * Date: 14-7-1
 * Time: 上午9:06
 * To change this template use File | Settings | File Templates.
 */
public class SchedulerExample {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private MyTask myTask;

    public void schedule(){
        try {
            // create JOB
            MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
            jobDetail.setTargetObject(myTask);
            jobDetail.setTargetMethod("performAction");
            jobDetail.setName("MyJobDetail");
            jobDetail.setConcurrent(false);
            jobDetail.afterPropertiesSet();

                /* SimpleTriggerBean trigger = new SimpleTriggerBean();
                trigger.setBeanName("MyTrigger");
                trigger.setJobDetail((JobDetail) jobDetail.getObject());
                trigger.setRepeatInterval(5000);
                trigger.afterPropertiesSet();
                */

            // create CRON Trigger
            CronTriggerBean cronTrigger = new CronTriggerBean();
            cronTrigger.setBeanName("CRON0001");

            // Execute after each 5 second
            String expression = "*/5 * * * * ?";
            cronTrigger.setCronExpression(expression);
            cronTrigger.afterPropertiesSet();

            //scheduler.scheduleJob(jobDetail, cronTrigger);

            scheduler.scheduleJob((JobDetail) jobDetail.getObject(), cronTrigger);

            // Start Scheduler
            scheduler.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
